﻿<%@ WebHandler Language="C#" Class="customDistributList" %>

using System;
using System.Web;
using System.Text;
using System.Collections.Generic;
using System.Data;
using Chenxin.Lib.Utility;
public class customDistributList : AjaxHandlerBase
{
    public customDistributList()
    {
        htTypePermit.Add("add", Constants.Permit_Allot_Add);
    }

    override public void RequestProcess(HttpContext context)
    {
        string strOp = context.Request["op"];
        string strResponse = "";
        switch (strOp.ToLower())
        {
            case "getlist":     //页面查询结果集Table
                //strResponse = getlist(context);
                strResponse = GetList(context);
                break;
            case "add":         //添加分配
                strResponse = add(context);
                break;
            case "getcustomerlist":         //根据查询显示客需列表
                strResponse = getcustomerlist(context);
                break;
            case "getallooptype":       //判断下拉框验证（到店/人）
                strResponse = check(context);
                break;
            default:
                break;
        }
        context.Response.ContentType = "text/plain";
        context.Response.Buffer = true;
        context.Response.ExpiresAbsolute = DateTime.Now.AddDays(-1);
        context.Response.AddHeader("pragma", "no-cache");
        context.Response.AddHeader("cache-control", "");
        context.Response.CacheControl = "no-cache";
        context.Response.Write(strResponse);
    }

    private string check(HttpContext context)
    {
        try
        {
            if (CurrentUserInfo.ContainsPermit(Chenxin.Lib.Utility.Constants.Permit_Allot_Depart_AllUser))
                return "{success:1,msg:'',data:{byuser:false}}";            
            else
                return "{success:1,msg:'',data:{byuser:true}}";
        }
        catch (Exception ex)
        {
            return "{success:0,msg:'" + ex.Message + "',data:{byuser:true}}";
        }
    }

    private string GetList(HttpContext context)
    {
        try
        {
            int iPageIndex = (string.IsNullOrEmpty(context.Request["pageindex"])) ? 1 : int.Parse(context.Request["pageindex"]) + 1;//页码
            int iPageSize = (string.IsNullOrEmpty(context.Request["pagesize"])) ? 30 : int.Parse(context.Request["pagesize"]);//页记录数

            string fieldlist = "RecordID,CustomerCode,CustomerName,OldPerson,OldDepart,OldCompany,OldCity,NowPerson,NowDepart,NowCompany,NowCity,OperPerson,OperTime";
            string fieldtablelist = "RecordID,CustomerCode,CustomerName,OldPerson,OldDepart,OldCompany,OldCity,NowPerson,NowDepart,NowCompany,NowCity,OperPerson,OperTime";
            string orderfield = "Customer_AllotLogs.OperTime desc";

            Guid cityId = (string.IsNullOrEmpty(context.Request["cityid"])) ? Guid.Empty : new Guid(context.Request["cityid"]);
            Guid companyId = (string.IsNullOrEmpty(context.Request["companyid"])) ? Guid.Empty : new Guid(context.Request["companyid"]);
            Guid areaId = (string.IsNullOrEmpty(context.Request["areaid"])) ? Guid.Empty : new Guid(context.Request["areaId"]);
            Guid departId = (string.IsNullOrEmpty(context.Request["departid"])) ? Guid.Empty : new Guid(context.Request["departid"]);
            Guid userId = (string.IsNullOrEmpty(context.Request["userid"])) ? Guid.Empty : new Guid(context.Request["userid"]);

            //判断权限范围/////////////////////////////////////////////
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            if (userId != Guid.Empty)
                sb.AppendFormat(" AND (OperPersonID = '{0}') ", userId);
            else if (departId != Guid.Empty)
                sb.AppendFormat(" AND (OperDepartId = '{0}')", departId);
            else if (areaId != Guid.Empty)
            {
                Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo item = null;
                string strCachkey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_DEPARTMENT, areaId);
                Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
                item = cs.GetObject<Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo>(strCachkey);
                if (!cs.Hit)
                {
                    item = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetModel(areaId);
                    if (item != null) cs.Set(strCachkey, item, DateTime.Now.AddDays(1));
                }

                if (item == null) return string.Format("{{success:'0',msg:'{0}',data:''}}", "获取商圈或分类数据丢失");

                sb.AppendFormat(" AND (OperDepartId in (select departId from v_Hr_DepartmentInfo where DepartSrc like '{0}%'))", item.DepartSrc);
            }
            else if (companyId != Guid.Empty)
                sb.AppendFormat(" AND OperCompanyId = '{0}'", companyId);
            else if (cityId != Guid.Empty)
                sb.AppendFormat(" AND OperCityId = '{0}'", cityId);
            else
                sb.AppendFormat(" AND OperCompanyId = '{0}'", CurrentUserInfo.CompanyId);

            System.Text.StringBuilder sb1 = new System.Text.StringBuilder();
            //查看所有分配客需权限
            if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewAllAllotDemand))
            {
                sb1.Append(" (1=1) ");
            }
            //查看城市分配客需权限
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewCityAllotDemand))
            {
                sb1.AppendFormat(" OperCityId= '{0}' ", CurrentUserInfo.CityId);
            }
            //查看公司分配客需权限
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewCompanyAllotDemand))
            {
                sb1.AppendFormat(" OperCompanyId= '{0}' ", CurrentUserInfo.CompanyId);
            }
            //查看部门分配客需权限
            //else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewDepartAllotDemand))
            //{
            //    sb1.Append("EXISTS(");
            //    sb1.Append("Select 1 from v_Struct_UserDepartRelation M ");
            //    sb1.AppendFormat("WHERE (Customer_AllotLogs.OperDepartId = M.Departid AND  M.Userid= '{0}') ", CurrentUserInfo.UserId);
            //    sb1.Append(")");
            //}
            else
            {
                sb1.AppendFormat(" OperPersonID = '{0}'", CurrentUserInfo.UserId);
            }

            if (!String.IsNullOrEmpty(sb.ToString()))
                sb1.Append(sb.ToString());

            string stime = context.Request.QueryString["stime"];
            string etime = context.Request.QueryString["etime"];
            string usercode = context.Request.QueryString["usercode"];


            if (!String.IsNullOrEmpty(stime))
            {
                sb1.Append(string.Format(" AND convert(varchar(10),(convert(datetime,OperTime,120)),120)  >= '{0}'", (stime)));
            }
            if (!String.IsNullOrEmpty(etime))
            {
                sb1.Append(string.Format(" AND convert(varchar(10),(convert(datetime,OperTime,120)),120)  <= '{0}'", (etime)));
            }
            if (!String.IsNullOrEmpty(usercode))
            {
                sb1.Append(string.Format(" and OldPersonID =(select UserId from v_Hr_User_BaseInfo where UserCode= '{0}')", usercode));
            }


            //判断权限范围结束////////////////////////////////////////////
            System.Data.DataSet list = null;
            list = Chenxin.Lib.House.DAL.Customer_AllotLogs.GetList(
                iPageIndex, iPageSize, orderfield, "Customer_AllotLogs", sb1.ToString(), fieldlist, fieldtablelist, true);
            int count = (int)list.Tables[1].Rows[0][0];


            return string.Format("{{success:1,msg:'',data:{{count:{0},{1}}}}}", count, JsonHelp.Convert2Json(list.Tables[0]));
            
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message);
        }        
    }
    

    //查询分配记录结果集
    private string getlist(HttpContext context)
    {
        try
        {
            int iPageIndex = (string.IsNullOrEmpty(context.Request["pageindex"])) ? 1 : int.Parse(context.Request["pageindex"]) + 1;//页码
            int iPageSize = (string.IsNullOrEmpty(context.Request["pagesize"])) ? 30 : int.Parse(context.Request["pagesize"]);//页记录数

            string fieldlist = "RecordID,CustomerCode,CustomerName,OldPerson,OldDepart,OldCompany,OldCity,NowPerson,NowDepart,NowCompany,NowCity,OperPerson,OperTime";
            string fieldtablelist = "RecordID,CustomerCode,CustomerName,OldPerson,OldDepart,OldCompany,OldCity,NowPerson,NowDepart,NowCompany,NowCity,OperPerson,OperTime";
            string orderfield = "Customer_AllotLogs.OperTime desc";

            Guid cityId = (string.IsNullOrEmpty(context.Request["cityid"])) ? Guid.Empty : new Guid(context.Request["cityid"]);
            Guid companyId = (string.IsNullOrEmpty(context.Request["companyid"])) ? Guid.Empty : new Guid(context.Request["companyid"]);
            Guid areaId = (string.IsNullOrEmpty(context.Request["areaid"])) ? Guid.Empty : new Guid(context.Request["areaId"]);
            Guid departId = (string.IsNullOrEmpty(context.Request["departid"])) ? Guid.Empty : new Guid(context.Request["departid"]);
            Guid userId = (string.IsNullOrEmpty(context.Request["userid"])) ? Guid.Empty : new Guid(context.Request["userid"]);

            //判断权限范围/////////////////////////////////////////////
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            if (userId != Guid.Empty)
                sb.AppendFormat(" AND (OperPersonID = '{0}') ", userId);
            else if (departId != Guid.Empty)
                sb.AppendFormat(" AND (OperDepartId = '{0}')", departId);
            else if (areaId != Guid.Empty)
            {
                Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo item = null;
                string strCachkey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_DEPARTMENT, areaId);
                Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
                item = cs.GetObject<Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo>(strCachkey);
                if (!cs.Hit)
                {
                    item = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetModel(areaId);
                    if (item != null) cs.Set(strCachkey, item, DateTime.Now.AddDays(1));
                }

                if (item == null) return string.Format("{{success:'0',msg:'{0}',data:''}}", "获取商圈或分类数据丢失");

                sb.AppendFormat(" AND (OperDepartId in (select departId from v_Hr_DepartmentInfo where DepartSrc like '{0}%'))", item.DepartSrc);
            }
            else if (companyId != Guid.Empty)
                sb.AppendFormat(" AND OperCompanyId = '{0}'", companyId);
            else if (cityId != Guid.Empty)
                sb.AppendFormat(" AND OperCityId = '{0}'", cityId);
            else
                sb.AppendFormat(" AND OperCompanyId = '{0}'", CurrentUserInfo.CompanyId);

            System.Text.StringBuilder sb1 = new System.Text.StringBuilder();
            //查看所有分配客需权限
            if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewAllAllotDemand))
            {
                sb1.Append(" (1=1) ");
            }
            //查看城市分配客需权限
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewCityAllotDemand))
            {
                sb1.AppendFormat(" OperCityId= '{0}' ", CurrentUserInfo.CityId);
            }
            //查看公司分配客需权限
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewCompanyAllotDemand))
            {
                sb1.AppendFormat(" OperCompanyId= '{0}' ", CurrentUserInfo.CompanyId);
            }
            //查看部门分配客需权限
            //else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewDepartAllotDemand))
            //{
            //    sb1.Append("EXISTS(");
            //    sb1.Append("Select 1 from v_Struct_UserDepartRelation M ");
            //    sb1.AppendFormat("WHERE (Customer_AllotLogs.OperDepartId = M.Departid AND  M.Userid= '{0}') ", CurrentUserInfo.UserId);
            //    sb1.Append(")");
            //}
            else
            {
                sb1.AppendFormat(" OperPersonID = '{0}'", CurrentUserInfo.UserId);
            }
            
            if (!String.IsNullOrEmpty(sb.ToString()))
                sb1.Append(sb.ToString());

            string stime = context.Request.QueryString["stime"];
            string etime = context.Request.QueryString["etime"];
            string usercode = context.Request.QueryString["usercode"];
            

            if (!String.IsNullOrEmpty(stime))
            {
                sb1.Append(string.Format(" AND convert(varchar(10),(convert(datetime,OperTime,120)),120)  >= '{0}'", (stime)));
            }
            if (!String.IsNullOrEmpty(etime))
            {
                sb1.Append(string.Format(" AND convert(varchar(10),(convert(datetime,OperTime,120)),120)  <= '{0}'", (etime)));
            }
            if (!String.IsNullOrEmpty(usercode))
            {
                sb1.Append(string.Format(" and OldPersonID =(select UserId from v_Hr_User_BaseInfo where UserCode= '{0}')", usercode));
            }
            
            
            //判断权限范围结束////////////////////////////////////////////
            System.Data.DataSet list = null;
            list = Chenxin.Lib.House.DAL.Customer_AllotLogs.GetList(
                iPageIndex, iPageSize, orderfield, "Customer_AllotLogs", sb1.ToString(), fieldlist, fieldtablelist, true);
            int count = (int)list.Tables[1].Rows[0][0];
            string strHtml = "";
            if (!GetKeyListHtml(list, out strHtml))
            {
                return string.Format("{{success:'0',msg:'{0}',data:''}}", "生成HTML错误:" + strHtml);
            }
            list.Dispose();
            list = null;
            return string.Format("{{success:'1',msg:'{0}',data:{{count:'{1}',data:'{2}'}}}}", "成功", count, strHtml);
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message);
        }
    }

    /// <summary>
    /// 返回列表；
    /// 根据查询参数生成查询条件1,根据权限设定生成查询条件2；
    /// 返回Json数据：{count:'30',data:'abc'}
    /// </summary>
    /// <param name="context"></param>
    private bool GetKeyListHtml(System.Data.DataSet dslist, out string strHtml)
    {
        try
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("<table height=\"100%\" cellspacing=\"1\" class=\"tabsorternew\" id=\"report\" style=\"width:1000px;\">");
            sb.Append("<thead><tr>");
            //sb.Append("<th width=\"100\">客户编号</th>");
            sb.Append("<th width=\"80\">客户姓名</th>");
            sb.Append("<th width=\"60\" >原所属人</th>");
            sb.Append("<th width=\"60\" >原门店</th>");
            sb.Append("<th width=\"60\" >原公司</th>");
            sb.Append("<th width=\"60\" >原城市</th>");
            sb.Append("<th width=\"60\">现所属人</th>");
            sb.Append("<th width=\"60\">现门店</th>");
            sb.Append("<th width=\"60\" >现公司</th>");
            sb.Append("<th width=\"60\" >现城市</th>");
            sb.Append("<th width=\"60\">操作人</th>");
            sb.Append("<th width=\"80\">操作时间</th>");
            sb.Append("</tr></thead><tbody>");
                
            foreach (System.Data.DataRow row in dslist.Tables[0].Rows)
            {
                sb.AppendFormat("<tr id=\"{0}\" class=\"tr_houselist\">", row["RecordID"].ToString());
                //sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "CustomerCode", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "CustomerName", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "OldPerson", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "OldDepart", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "OldCompany", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "OldCity", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "NowPerson", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "NowDepart", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "NowCompany", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "NowCity", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "OperPerson", ""));
                sb.AppendFormat("<td>{0:yyyy-MM-dd}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "OperTime", ""));

                sb.Append("</tr>");
            }

            sb.Append("</tbody></table>");
            strHtml = sb.ToString();
            return true;
        }
        catch (Exception ex)
        {
            strHtml = ex.Message;
            return false;
        }
    }


    /// <summary>
    /// 返回列表；
    /// 根据查询参数生成查询条件1,根据权限设定生成查询条件2；
    /// 返回Json数据：{count:'30',data:'abc'}
    /// </summary>
    /// <param name="context"></param>
    private string add(HttpContext context)
    {
        try
        {
            string allotStyle = context.Request["allotStyle"];

            Chenxin.Lib.House.Entity.Customer_AllotLogs model = (Chenxin.Lib.House.Entity.Customer_AllotLogs)JsonHelp.Convert2Entity(context.Request["model"], typeof(Chenxin.Lib.House.Entity.Customer_AllotLogs));

            if (model.NowCityId == Guid.Empty || model.NowCompanyId == Guid.Empty || model.NowDepartID == Guid.Empty )
            {
                return string.Format("{{success:'0',msg:'请填写完整数据,目标城市、公司、部门都不能为空！',data:''}}");
            }

            if (model.NowDepartID != model.OldDepartID)
            {
                if (!CurrentUserInfo.ContainsPermit(Constants.Permit_AllotHouse_Over))
                {
                    return string.Format("{{success:'0',msg:'不能夸门店转客需！',data:''}}");
                }
            }
            
            if (!string.IsNullOrEmpty(model.NowPerson))
                model.NowPerson = model.NowPerson.Remove(model.NowPerson.IndexOf("("));
            if (!string.IsNullOrEmpty(model.OldPerson))
                model.OldPerson = model.OldPerson.Remove(model.OldPerson.IndexOf("("));
            
            //快速分配
            if ("10".Equals(allotStyle))
            {

                string allotType = context.Request["allotType"];

                //人
                if ("10".Equals(allotType))
                {
                    if (!DemandInfoToUser(model))
                    {
                        return string.Format("{{success:'0',msg:'{0}',data:''}}", "没有可分配的客需！");
                    }
                    else
                    {
                        AddLog("" + CurrentUserInfo.UserName + "快速分配客需:已分配给人["+model.NowPerson+"]",
                         OperationType.OperationTypeComboList()["OprType_CustomerAllot"].ToString());
                    }
                }//店
                else if ("20".Equals(allotType))
                {
                    if (!DemandInfoToDep(model))
                    {
                        return string.Format("{{success:'0',msg:'{0}',data:''}}", "没有可分配的客需！");
                    }
                    else
                    {
                        AddLog("" + CurrentUserInfo.UserName + "快速分配客需:已全部分配给店[" + model.NowDepart + "]",
                         OperationType.OperationTypeComboList()["OprType_CustomerAllot"].ToString());
                    }
                }
                //平均 
                else
                {
                    int flg = DemandInfoToAvg(model);
                    if (1 == flg)
                    {
                        return string.Format("{{success:'0',msg:'{0}',data:''}}", "没有可分配的客需！");
                    }
                    else if (2 == flg)
                    {
                        return string.Format("{{success:'0',msg:'{0}',data:''}}", "接受门店没有可接受的员工！");
                    }
                    else
                    {
                        AddLog("" + CurrentUserInfo.UserName + "快速分配客需:已平均分配给店[" + model.NowDepart + "]",
                         OperationType.OperationTypeComboList()["OprType_CustomerAllot"].ToString());
                    }
                }
            }
            else
            {
                string houseid = context.Request["houseIdList"];
                int flg = DemandInfoByHand(houseid, model);
                if (1 == flg)
                {
                    return string.Format("{{success:'0',msg:'{0}',data:''}}", "没有可分配的客需！");
                }
                else 
                {
                    AddLog("" + CurrentUserInfo.UserName + "手动分配客需:已分配给人[" + model.NowPerson + "]",
                         OperationType.OperationTypeComboList()["OprType_CustomerAllot"].ToString());
                }
            }

            return string.Format("{{success:'1',msg:'{0}',data:''}}", "分配成功！");
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message);
        }
    }

    //快速分配客需给某人
    private bool DemandInfoToUser(Chenxin.Lib.House.Entity.Customer_AllotLogs model)
    {
        StringBuilder sb = new StringBuilder();
        string str = "";
        if (model.OldPersonID != null && model.OldPersonID != Guid.Empty)
            str = string.Format(" and Customer_DemandInfo.OprPersonId='{0}'", model.OldPersonID.ToString());
        
        string strSql = "";
        //添加客需分配日志并修改原房源记录
        strSql += string.Format("insert into Customer_AllotLogs select newid(),CustomerId,CustomerCode,CustomerName,OprPersonId,OprPerson,Customer_DemandInfo.cityid,Customer_DemandInfo.CityName,Customer_DemandInfo.CompanyId,Customer_DemandInfo.CompanyName,OprDepartId,OprDepart,'{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}',getdate() from Customer_DemandInfo where OprDepartId='{16}'{17};", model.NowPersonID.ToString(), model.NowPerson, model.NowCityId.ToString(), model.NowCity, model.NowCompanyId.ToString(), model.NowCompany, model.NowDepartID.ToString(), model.NowDepart, CurrentUserInfo.UserId.ToString(), CurrentUserInfo.UserName, CurrentUserInfo.CityId.ToString(), CurrentUserInfo.CityName, CurrentUserInfo.CompanyId.ToString(), CurrentUserInfo.CompanyName, CurrentUserInfo.DepartId.ToString(), CurrentUserInfo.DepartName,model.OldDepartID.ToString(),str);
        strSql += string.Format("update Customer_BaseInfo set OprPerson='{0}',OprPersonId='{1}',OprDepart='{2}',OprDepartId='{3}',Customer_BaseInfo.CompanyId='{4}',Customer_BaseInfo.CompanyName='{5}',CityId='{8}',CityName='{9}' from dbo.Customer_BaseInfo,Customer_DemandInfo where Customer_DemandInfo.CustomerId=Customer_BaseInfo.CustomerId and Customer_DemandInfo.OprDepartId='{6}'{7};", model.NowPerson, model.NowPersonID.ToString(), model.NowDepart, model.NowDepartID.ToString(), model.NowCompanyId.ToString(), model.NowCompany, model.OldDepartID.ToString(), str, model.NowCityId.ToString(), model.NowCity);

        strSql += string.Format("update Customer_DemandInfo set OprPerson='{0}',OprPersonId='{1}',OprDepart='{2}',OprDepartId='{3}',CompanyId='{4}',CompanyName='{5}',CityId='{6}',CityName='{7}' where OprDepartId='{8}'{9};", model.NowPerson, model.NowPersonID.ToString(), model.NowDepart, model.NowDepartID.ToString(), model.NowCompanyId.ToString(), model.NowCompany,  model.NowCityId.ToString(), model.NowCity,model.OldDepartID.ToString(),str);

        return Chenxin.Lib.House.DAL.House_BaseInfo.ExecuteSQL(strSql);
    }

    //快速分配客需给某店
    private bool DemandInfoToDep(Chenxin.Lib.House.Entity.Customer_AllotLogs model)
    {
        StringBuilder sb = new StringBuilder();
        string strSql = "";
        string str = "";
        if (model.OldPersonID != null && model.OldPersonID != Guid.Empty)
            str = string.Format(" and Customer_DemandInfo.OprPersonId='{0}'", model.OldPersonID.ToString());
        
        //添加客需分配日志并修改原房源记录
        strSql += String.Format("insert into Customer_AllotLogs select newid(),CustomerId,CustomerCode,CustomerName,OprPersonId,OprPerson,Customer_DemandInfo.cityid,Customer_DemandInfo.CityName,Customer_DemandInfo.CompanyId,Customer_DemandInfo.CompanyName,OprDepartId,OprDepart,OprPersonId,OprPerson,'{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}',getdate() from Customer_DemandInfo where OprDepartId='{14}'{15};", model.NowCityId.ToString(), model.NowCity, model.NowCompanyId.ToString(), model.NowCompany, model.NowDepartID.ToString(), model.NowDepart, CurrentUserInfo.UserId.ToString(), CurrentUserInfo.UserName, CurrentUserInfo.CityId.ToString(), CurrentUserInfo.CityName, CurrentUserInfo.CompanyId.ToString(), CurrentUserInfo.CompanyName, CurrentUserInfo.DepartId.ToString(), CurrentUserInfo.DepartName, model.OldDepartID.ToString(),str);
        strSql += string.Format("update Customer_BaseInfo set OprDepart='{0}',OprDepartId='{1}',Customer_BaseInfo.CompanyId='{2}',Customer_BaseInfo.CompanyName='{3}',CityId='{6}',CityName='{7}' from dbo.Customer_BaseInfo,Customer_DemandInfo where Customer_DemandInfo.CustomerId=Customer_BaseInfo.CustomerId and Customer_DemandInfo.OprDepartId='{4}'{5};", model.NowDepart, model.NowDepartID.ToString(), model.NowCompanyId.ToString(), model.NowCompany, model.OldDepartID.ToString(), str, model.NowCityId.ToString(), model.NowCity);

        strSql += string.Format("update Customer_DemandInfo set OprDepart='{0}',OprDepartId='{1}',CompanyId='{2}',CompanyName='{3}',CityId='{4}',CityName='{5}' where OprDepartId='{6}'{7};", model.NowDepart, model.NowDepartID.ToString(), model.NowCompanyId.ToString(), model.NowCompany, model.NowCityId.ToString(), model.NowCity,model.OldDepartID.ToString(),str);

        return Chenxin.Lib.House.DAL.House_BaseInfo.ExecuteSQL(strSql);
    }

    //平均分配客需
    private int DemandInfoToAvg(Chenxin.Lib.House.Entity.Customer_AllotLogs model)
    {
        StringBuilder sb = new StringBuilder();
        string housecount_sql = "OprDepartId='"+model.OldDepartID.ToString()+"'";
        if (model.OldPersonID != null && model.OldPersonID != Guid.Empty)
            housecount_sql += " and OprPersonId='" + model.OldPersonID.ToString()+"'";
        string usercount_sql = String.Format("DepartId='{0}' and Status='1' and IsVirtual='0' and validate=1 "
            + "and userid in (select UserId from dbo.Struct_UserDepartRelation where DepartId='{0}' and isbelong=1 and IsRoleA=1)", model.NowDepartID.ToString());
        DataSet house_ds = Chenxin.Lib.House.DAL.Customer_DemandInfo.GetList(housecount_sql);
        DataSet user_ds = Chenxin.Lib.Passport.DAL.Hr_UserInfo.GetList(usercount_sql);
        int house_sum = house_ds.Tables[0].Rows.Count;
        int user_sum = user_ds.Tables[0].Rows.Count;

        if (house_sum == 0)
            return 1;
        else if (user_sum == 0)
            return 2;
        else
        {
            string str = "";
            for (int i = 0; i < house_sum; )
            {
                for (int j = 0; j < user_sum; j++)
                {
                    if (i >= house_sum)
                        break;
                    str += string.Format("insert into Customer_AllotLogs select newid(),CustomerId,CustomerCode,CustomerName,OprPersonId,OprPerson,Customer_DemandInfo.cityid,Customer_DemandInfo.CityName,Customer_DemandInfo.CompanyId,Customer_DemandInfo.CompanyName,OprDepartId,OprDepart,'{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}',getdate() from Customer_DemandInfo where CustomerId='{16}';", user_ds.Tables[0].Rows[j]["UserId"], user_ds.Tables[0].Rows[j]["UserName"], model.NowCityId.ToString(), model.NowCity, model.NowCompanyId.ToString(), model.NowCompany, model.NowDepartID.ToString(), model.NowDepart, CurrentUserInfo.UserId, CurrentUserInfo.UserName, CurrentUserInfo.CityId.ToString(), CurrentUserInfo.CityName, CurrentUserInfo.CompanyId.ToString(), CurrentUserInfo.CompanyName, CurrentUserInfo.DepartId.ToString(), CurrentUserInfo.DepartName, house_ds.Tables[0].Rows[i]["CustomerId"]);

                    str += string.Format("update Customer_BaseInfo set OprPerson='{0}',OprPersonId='{1}',OprDepart='{2}',OprDepartId='{3}',Customer_BaseInfo.CompanyId='{4}',Customer_BaseInfo.CompanyName='{5}',CityId='{7}',CityName='{8}' from dbo.Customer_BaseInfo,Customer_DemandInfo where Customer_DemandInfo.CustomerId=Customer_BaseInfo.CustomerId and Customer_DemandInfo.CustomerId='{6}';", user_ds.Tables[0].Rows[j]["UserName"], user_ds.Tables[0].Rows[j]["UserId"], model.NowDepart, model.NowDepartID.ToString(), model.NowCompanyId.ToString(), model.NowCompany, house_ds.Tables[0].Rows[i]["CustomerId"], model.NowCityId.ToString(), model.NowCity);
                    str += string.Format("update Customer_DemandInfo set OprPerson='{0}',OprPersonId='{1}',OprDepart='{2}',OprDepartId='{3}',CompanyId='{4}',CompanyName='{5}',CityId='{7}',CityName='{8}' where CustomerId='{6}';", user_ds.Tables[0].Rows[j]["UserName"], user_ds.Tables[0].Rows[j]["UserId"], model.NowDepart, model.NowDepartID.ToString(), model.NowCompanyId.ToString(), model.NowCompany, house_ds.Tables[0].Rows[i]["CustomerId"], model.NowCityId.ToString(), model.NowCity);

                    i++;
                }
            }
            bool flag = Chenxin.Lib.House.DAL.House_BaseInfo.ExecuteSQL(str);
            if (flag)
                return 0;
            else
                return 1;
        }
    }

    //手动分配客需给某人
    private int DemandInfoByHand(string houseid, Chenxin.Lib.House.Entity.Customer_AllotLogs model)
    {
        string strSql = "";
        houseid = houseid.Replace(",", "','");
        //添加客需的客户分配日志并修改客户记录
        strSql += string.Format("insert into Customer_AllotLogs select newid(),CustomerId,CustomerCode,CustomerName,OprPersonId,OprPerson,Customer_DemandInfo.cityid,Customer_DemandInfo.CityName,Customer_DemandInfo.CompanyId,Customer_DemandInfo.CompanyName,OprDepartId,OprDepart,'{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}',getdate() from Customer_DemandInfo where CustomerId in ('{16}');", model.NowPersonID.ToString(), model.NowPerson, model.NowCityId.ToString(), model.NowCity, model.NowCompanyId.ToString(), model.NowCompany, model.NowDepartID.ToString(), model.NowDepart, CurrentUserInfo.UserId.ToString(), CurrentUserInfo.UserName, CurrentUserInfo.CityId.ToString(), CurrentUserInfo.CityName, CurrentUserInfo.CompanyId.ToString(), CurrentUserInfo.CompanyName, CurrentUserInfo.DepartId.ToString(), CurrentUserInfo.DepartName, houseid);
        strSql += string.Format("update Customer_BaseInfo set OprPerson='{0}',OprPersonId='{1}',OprDepart='{2}',OprDepartId='{3}',Customer_BaseInfo.CompanyId='{4}',Customer_BaseInfo.CompanyName='{5}',CityId='{7}',CityName='{8}' from dbo.Customer_BaseInfo inner join (select CustomerId from Customer_DemandInfo where CustomerId in ('{6}'))a on Customer_BaseInfo.CustomerId =a.CustomerId;", model.NowPerson, model.NowPersonID.ToString(), model.NowDepart, model.NowDepartID.ToString(), model.NowCompanyId.ToString(), model.NowCompany, houseid, model.NowCityId.ToString(), model.NowCity);

        strSql += string.Format("update Customer_DemandInfo set OprPerson='{0}',OprPersonId='{1}',OprDepart='{2}',OprDepartId='{3}',CompanyId='{4}',CompanyName='{5}',CityId='{7}',CityName='{8}' where CustomerId in ('{6}');", model.NowPerson, model.NowPersonID.ToString(), model.NowDepart, model.NowDepartID.ToString(), model.NowCompanyId.ToString(), model.NowCompany, houseid, model.NowCityId.ToString(), model.NowCity);


        bool flag = Chenxin.Lib.House.DAL.House_BaseInfo.ExecuteSQL(strSql);
        if (flag)
            return 0;
        else
            return 1;
    }
    private string getcustomerlist(HttpContext context)
    {
        try
        {
            //string allotType = context.Request["allotType"];
            string allot_person = context.Request["OldPersonID"];
            string allot_dep = context.Request["OldDepartID"];
            string startDay = context.Request["startDay"];
            string endDay = context.Request["endDay"];
            string keyword = context.Request["keyword"];

            int iPageIndex = (string.IsNullOrEmpty(context.Request["pageindex"])) ? 1 : int.Parse(context.Request["pageindex"]) + 1;//页码
            int iPageSize = (string.IsNullOrEmpty(context.Request["pagesize"])) ? 3 : int.Parse(context.Request["pagesize"]);//页记录数
            string fieldlist = "CustomerId,Addtime,CustomerCode,CustomerName,OprPerson,OprDepart";
            string fieldtablelist = "CustomerId,CONVERT(varchar(12) , Addtime, 111 ) as Addtime,CustomerCode,CustomerName,OprPerson,OprDepart";
            string orderfield = "Customer_DemandInfo.Addtime desc";

            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("1=1");
            if (!string.IsNullOrEmpty(allot_person))
            {
                sb.Append(string.Format(" AND OprPersonId='{0}' and OprDepartId='{1}'", (allot_person),allot_dep));
            }
            if (!string.IsNullOrEmpty(startDay))
            {
                sb.Append(string.Format(" AND convert(varchar(10),(convert(datetime,Addtime,120)),120)  >= '{0}'", (startDay)));
            }
            if (!string.IsNullOrEmpty(endDay))
            {
                sb.Append(string.Format(" AND convert(varchar(10),(convert(datetime,Addtime,120)),120)  <= '{0}'", (endDay)));
            }
            if (!string.IsNullOrEmpty(keyword))
            {
                sb.AppendFormat(" and (CustomerName like '%{0}%' or CustomerCode like '%{0}%')", keyword);
            }
            
            System.Data.DataSet ds = null;
            ds = Chenxin.Lib.House.DAL.Customer_DemandInfo.GetList(iPageIndex, iPageSize, orderfield, "Customer_DemandInfo", sb.ToString(), fieldlist, fieldtablelist, true);
            int count = (int)ds.Tables[1].Rows[0][0];
            string strHtml = "";
            if (!GetListHtml(ds, out strHtml))
            {
                return string.Format("{{success:'0',msg:'{0}',data:''}}", "生成HTML错误");
            }
            ds.Dispose();
            ds = null;
            return string.Format("{{success:'1',msg:'{0}',data:{{count:'{1}',data:'{2}'}}}}", "成功", count, strHtml);
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'{0}',data:''}}", "未知错误：" + ex.Message);
        }
    }

    /// <summary>
    /// 生成列表
    /// </summary>
    /// <param name="dslist"></param>
    /// <param name="strHtml"></param>
    /// <returns></returns>
    private bool GetListHtml(System.Data.DataSet dslist, out string strHtml)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();

        sb.Append("<table  class=\"PublicTable\" id=\"table_pt\" width=\"100%\"><tr class=\"toolbar\"><th><input type=\"checkbox\" name=\"checkall\" id=\"checkall\" /></th><th>建档日期</th><th>客需编号</th><th>客户名称</th><th>业务员</th><th>门店</th></tr>");
        foreach (System.Data.DataRow row in dslist.Tables[0].Rows)
        {
            sb.Append(String.Format("<tr><td><input type=\"checkbox\" name=\"allotck\" value=\"{0}\"/></td><td>{1}</td><td>{2}</td><td>{3}</td><td>{4}</td><td>{5}</td></tr>", row["CustomerId"], row["Addtime"], row["CustomerCode"], row["CustomerName"], row["OprPerson"], row["OprDepart"]));
        }
        sb.Append("</table>");
        strHtml = sb.ToString();
        return true;
    }
}